const fs = require('fs');
const { join } = require('path');

"use strict";
window.preload = Object.create(null);

/**
 * 渲染目录
 * @param {string} path 路径
 * @param {string} name 名字
 */
function renderPath(path, name) {
    let prefix = name;
    let suffix = '';
    let extraIndex =  name.lastIndexOf('.');
    if (extraIndex > -1) {
        prefix = name.substring(0, extraIndex);
        suffix = name.substring(extraIndex);
    }

    let index = 0;
    while(fs.existsSync(join(path, `${prefix}-${index}${suffix}`))) {
        index += 1;
    }
    return join(path, `${prefix}-${index}${suffix}`);
}

/**
 * 保存文件
 * @param {string} name 文件名
 * @param {string} path 文件所在路径
 * @param {ArrayBuffer} content 文件内容
 * @param {Function} callback 
 */
window.preload['saveFile'] = function (name, path, content, callback) {
    let re = join(path, name);
    if (fs.existsSync(re)) {
        re = renderPath(path, name);
    }
    fs.writeFile(re, new DataView(content), {}, callback);
}

